package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.common.vo.LoginUserVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 购物车拦截器，判断用户登录状态
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 在目标方法执行之前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        LoginUserVo loginUser = JwtUtils.getUser(request, AuthServerConstant.LOGIN_USER);

        //使用JwtToken替代Spring的分布式Session
        //HttpSession session = request.getSession();
        //MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);

        //获取客户端传来的userKey[临时用户的key]
        String userKey = request.getHeader("userKey");

        if (loginUser != null) {
            //用户已登录
            userInfoTo.setUserId(loginUser.getId());
        }

        if (!StringUtils.isBlank(userKey)) {
            userInfoTo.setUserKey(userKey);
        } else {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        threadLocal.set(userInfoTo);
        return true;
    }
}
